package com.hifar.test.report.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.model.VO.IdVO;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.sys.*;
import com.hifar.test.entrust.constant.EntrustConsts;
import com.hifar.test.entrust.constant.ReportConsts;
import com.hifar.test.entrust.pojo.HfEnvEntrust;
import com.hifar.test.entrust.pojo.HfEnvGkEntrust;
import com.hifar.test.entrust.pojo.VO.HfEnvEntrustVO;
import com.hifar.test.entrust.pojo.VO.HfEnvGkEntrustVO;
import com.hifar.test.entrust.service.IHfEnvEntrustService;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.report.pojo.HfEnvReport;
import com.hifar.test.report.pojo.VO.*;
import com.hifar.test.report.service.IHfEnvReportService;
import com.tssk.kylx.fw.utils.lang.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhuWeiWei
 * @description 环境报告
 * @date 2024/12/26 13:46
 */
@RestController
@RequestMapping("/api/busi/test/envReport")
@Api("环境报告")
public class HfEnvReportController {
    @Autowired
    private IHfEnvReportService envReportService;
    @Autowired
    private IHfEnvEntrustService envEntrustService;
    @Autowired
    private IHfEnvGkEntrustService gkEntrustService;

    @Autowired
    private MinioUtil minioUtil;

    @PostMapping("/listPage")
    @ApiOperation("报告模块:列表查询")
    public BusiResponse listPage(@RequestBody QueryParamsVO queryParam) {
        QueryParamBean<HfEnvReportVO> queryParamBean = new QueryParamBean(queryParam);
        queryParamBean.addColumns(HfEnvReport.class, "r");
        queryParamBean.addColumns(HfEnvGkEntrust.class, "e");
        QueryWrapper<HfEnvReportVO> queryWrapper = queryParamBean.getQueryWrapper();
        queryWrapper.orderByDesc("r.create_time");
        Page page = queryParamBean.getPage();
        Page<HfEnvReportVO> pageData = envReportService.pageVO(page, queryWrapper);
        List<HfEnvReportVO> records = pageData.getRecords();
        for (HfEnvReport record : records) {
            String pdfPath = record.getPdfPath();
            String wordPath = record.getWordPath();
            Integer secretLevel = record.getSecretLevel();
            String newPdfPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, pdfPath, secretLevel);
            String newWordPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, wordPath, secretLevel);
            record.setPdfPath(newPdfPath);
            record.setWordPath(newWordPath);
        }
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @PostMapping("/submitReport")
    @ApiOperation("报告模块:提交审批")
    public BusiResponse submitReport(@RequestBody @Validated IdVO idVO) {
        envReportService.submitReport(idVO.getId());
        return BusiResponse.OK();
    }

    @PostMapping("/examinePass")
    @ApiOperation("报告模块:审核通过")
    public BusiResponse examinePass(@RequestBody @Validated ReportApproveVO reportApproveVO) {
        envReportService.examinePass(reportApproveVO);
        return BusiResponse.OK();
    }


    @PostMapping("/examineReject")
    @ApiOperation("报告模块:审核驳回")
    public BusiResponse examineReject(@RequestBody @Validated ReportApproveVO reportApproveVO) {
        envReportService.examineReject(reportApproveVO);
        return BusiResponse.OK();
    }

    @PostMapping("/approveReject")
    @ApiOperation("报告模块:批准驳回")
    public BusiResponse approveReject(@RequestBody @Validated ReportApproveVO reportApproveVO) {
        envReportService.approveReject(reportApproveVO);
        return BusiResponse.OK();
    }

    @PostMapping("/approvePass")
    @ApiOperation("报告模块:批准通过")
    public BusiResponse approvePass(@RequestBody @Validated ReportApproveVO reportApproveVO) {
        envReportService.approvePass(reportApproveVO);
        return BusiResponse.OK();
    }


    @GetMapping("/queryById")
    @ApiOperation("报告模块:查询详情")
    public BusiResponse<HfEnvReport> queryById(@RequestParam("id") String id) {
        HfEnvReport envReport = envReportService.getById(id);
        Assert.notNull(envReport, "报告数据不存在!");
        String pdfPath = envReport.getPdfPath();
        String wordPath = envReport.getWordPath();
        Integer secretLevel = envReport.getSecretLevel();
        String newPdfPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, pdfPath, secretLevel);
        String newWordPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, wordPath, secretLevel);
        envReport.setPdfPath(newPdfPath);
        envReport.setWordPath(newWordPath);
        return BusiResponse.OK(envReport);
    }

    @PostMapping("/generateReport")
    @ApiOperation("报告模板:报告生成")
    public BusiResponse generateReport(@RequestBody @Validated ReportCreateVO reportCreateVO) {
        envReportService.generateReport(reportCreateVO);
        return BusiResponse.OK();
    }

    @PostMapping("/listPageReport")
    @ApiOperation("报告生成:审核列表")
    public BusiResponse listPageReport(@RequestBody @Validated HfEnvReportQueryParamVO queryParamVO) {
        QueryParamBean<HfEnvReportVO> queryParamBean = new QueryParamBean(queryParamVO);
        queryParamBean.addColumns(HfEnvReport.class, "r");
        queryParamBean.addColumns(HfEnvGkEntrust.class, "e");
        String type = queryParamVO.getType();
        QueryWrapper<HfEnvReportVO> queryWrapper = queryParamBean.getQueryWrapper();

        String userId = SystemLoginUser.userId;

        if (Objects.equals(ReportConsts.REPORT_QUERY_TYPE_PENDING_APPROVED, type)) {
            // 待审核
            queryWrapper.eq("r.status", ReportConsts.REPORT_STATUS_TJ);
        } else if (Objects.equals(ReportConsts.REPORT_QUERY_TYPE_AUDITED, type)) {
            // 已审核
            queryWrapper.in("r.status", ReportConsts.REPORT_STATUS_DPZ, ReportConsts.REPORT_STATUS_SHBH, ReportConsts.REPORT_STATUS_PZBH);
            queryWrapper.apply(" exists ( select 1 from hf_env_report_record rr " +
                            " where r.id=rr.report_id and rr.opt_type in ({0},{1}) and rr.create_user_id={2} ) "
                    , ReportConsts.REPORT_OPT_TYPE_EXAMINE_PASS, ReportConsts.REPORT_OPT_TYPE_EXAMINE_REJECT, userId);

        } else if (Objects.equals(ReportConsts.REPORT_QUERY_TYPE_PENDING_APPROVAL, type)) {
            // 待批准
            queryWrapper.eq("r.status", ReportConsts.REPORT_STATUS_DPZ);
        } else if (Objects.equals(ReportConsts.REPORT_QUERY_TYPE_APPROVED, type)) {
            // 已批准
            queryWrapper.in("r.status", ReportConsts.REPORT_STATUS_PZTG, ReportConsts.REPORT_STATUS_PZBH);
            queryWrapper.apply(" exists ( select 1 from hf_env_report_record rr " +
                            " where r.id=rr.report_id and rr.opt_type in ({0},{1}) and rr.create_user_id={2} ) "
                    , ReportConsts.REPORT_OPT_TYPE_APPROVE_PASS, ReportConsts.REPORT_OPT_TYPE_APPROVE_REJECT, userId);
        }
        queryWrapper.orderByDesc("update_time");

        Page page = queryParamBean.getPage();
        Page<HfEnvReportVO> pageData = envReportService.pageVO(page, queryWrapper);
        List<HfEnvReportVO> records = pageData.getRecords();
        for (HfEnvReport record : records) {
            String pdfPath = record.getPdfPath();
            String wordPath = record.getWordPath();
            Integer secretLevel = record.getSecretLevel();
            String newPdfPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, pdfPath, secretLevel);
            String newWordPath = minioUtil.getFullFilePath(MinioUtil.PRE_DEFAULT, wordPath, secretLevel);
            record.setPdfPath(newPdfPath);
            record.setWordPath(newWordPath);
        }
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }


    @ApiOperation("删除")
    @PostMapping("/delete")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfEnvReport> reportList = envReportService.listByIds(idList);
        List<HfEnvReport> noDelReportList = reportList.stream()
                .filter(item -> !Objects.equals(item.getStatus(), ReportConsts.REPORT_STATUS_ERROR))
                .collect(Collectors.toList());
        if (!noDelReportList.isEmpty()) {
            String reportCodes = noDelReportList.stream()
                    .map(HfEnvReport::getReportCode)
                    .collect(Collectors.joining(","));
            return BusiResponse.error(500, String.format("报告%s不能删除!", reportCodes));
        }
        envReportService.removeByIds(idList);
        return BusiResponse.OK();
    }

    @ApiOperation("待生成报告委托单列表")
    @PostMapping("/entrustListPage")
    public BusiResponse entrustListPage(@RequestBody @Validated HfEnvReportQueryParamVO queryParamsVO) {
        QueryParamBean<HfEnvGkEntrustVO> queryParamBean = new QueryParamBean<>(queryParamsVO);
        String type = queryParamsVO.getType();
        queryParamBean.addColumns(HfEnvGkEntrust.class, "e");
        QueryWrapper<HfEnvGkEntrustVO> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfEnvGkEntrustVO> page = queryParamBean.getPage();
        queryWrapper.in("e.secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.eq("e.status", EntrustConsts.WTD_STATUS_YWC);
        queryWrapper.orderByDesc("e.create_time");
        // 1：未出 2：已出
        if (Objects.equals("2", type)) {
            queryWrapper.apply(" exists( select 1 from hf_env_report r " +
                            " where r.gk_entrust_id=e.id and r.del_flag={0} )"
                    , "0");
        } else {
            queryWrapper.apply(" not exists( select 1 from hf_env_report r " +
                            " where r.gk_entrust_id=e.id and r.del_flag={0} )"
                    , "0");
        }
        Page<HfEnvGkEntrustVO> pageData = gkEntrustService.pageVO(page, queryWrapper);
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);
    }

    @PostMapping("/replaceReport")
    public BusiResponse replaceReport(@RequestBody @Validated ReplaceReportVO replaceReportVO) {
        HfEnvReport hfEnvReport = envReportService.replaceReport(replaceReportVO.getId(), replaceReportVO.getFileId());
        String wordPath = hfEnvReport.getWordPath();
        String pdfPath = hfEnvReport.getPdfPath();
        Integer secretLevel = hfEnvReport.getSecretLevel();
        if (StringUtils.isNotBlank(wordPath)) {
            hfEnvReport.setWordPath(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, wordPath, secretLevel));
        }
        if (StringUtils.isNotBlank(pdfPath)) {
            hfEnvReport.setPdfPath(MinioUtil.getFullFilePaths(MinioUtil.PRE_DEFAULT, pdfPath, secretLevel));
        }
        return BusiResponse.OK(hfEnvReport);
    }


    @PostMapping("/pushReport")
    @ApiOperation("推送报告至ESB")
    public BusiResponse pushReport(@RequestBody @Validated ReportPushVO reportPushVO) {
        envReportService.pushReport(reportPushVO);
        return BusiResponse.OK();
    }

}
